<?php

namespace App\Console\Server;

use Illuminate\Console\Scheduling\Event as BaseEvent;
use App\Services\HallService;
use App\Jobs\Command;
use common\enum\QueueEnum;

class Event extends BaseEvent
{

    public $after;

    public $region;

    public $isHallCmd = false;

    public $isTickCmd = false;

    public $maxProcess = 1;

    public $queueName = QueueEnum::COMMAND;

    /**
     * 间隔s秒执行
     * 
     * @param int $s
     * @return $this
     */
    public function tick(int $s)
    {
        $this->after = $s;
        $this->isTickCmd = true;
        return $this;
    }

    /**
     * 随机间隔a-b秒执行
     * 
     * @param int $a
     * @param int $b
     * @return $this
     */
    public function randomTick(int $a, int $b)
    {
        if ($a > $b) {
            $this->region = [$b, $a];
        } else {
            $this->region = [$a, $b];
        }
        $this->isTickCmd = true;
        return $this;
    }

    /**
     * 多厅任务
     * 
     * @return $this
     */
    public function everyHall()
    {
        $this->isHallCmd = true;
        return $this;
    }

    public function onQueue($queueName)
    {
        $this->queueName = $queueName;
    }

    /**
     * 最大可同时运行线程数, 0为无限制，默认1，同一时间仅允许1条进程进行
     * 
     * @param int $maxProcess
     * @return $this
     */
    public function maxProcess(int $maxProcess){
        $this->maxProcess = $maxProcess;
        return $this;
    }

    /**
     * 获取执行间隔
     */
    public function getIntervalTime()
    {
        $t = 0;
        if ($this->after) {
            $t = $this->after;
        } elseif (!empty($this->region)) {
            $t = mt_rand($this->region[0], $this->region[1]);
        }
        return $t;
    }

    /**
     * 获取参数格式
     * 
     * @return array
     */
    public function getCmdArgs()
    {
        $args = explode(' ', $this->command);
        array_shift($args);
        return $args;
    }

    /**
     * 分发任务
     * 
     * @return array
     */
    public function dispatch()
    {
        // 厅任务
        if ($this->isHallCmd) {
            $halls = HallService::getValidHallIDs();
            foreach ($halls as $hallID) {
                $args = $this->getCmdArgs();
                array_push($args, '--hall_id=' . $hallID);
                dispatch((new Command($args, $this->maxProcess))->onQueue($this->queueName));
            }
        } else {
            $args = $this->getCmdArgs();
            dispatch((new Command($args, $this->maxProcess))->onQueue($this->queueName));
        }
    }
}
